<?php
/**
 * 员工管理控制器
 */

namespace app\admin\controller;

use app\common\model\Department;
use app\common\model\Insure;
use app\common\model\Position;
use think\Request;
use app\common\model\Staff;

use app\common\validate\StaffValidate;

class StaffController extends Controller
{

    //列表
    public function index(Request $request, Staff $model)
    {
        $param = $request->param();
        $model = $model->scope('where', $param)->with('department,insure,position')->order('department_id desc');
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['ID', '姓名', '职位', '社保关系', '档案编号', '手机号', '邮箱', '部门', '险种', '身份证号', '性别', '年龄', '生日', '生日月份', '户口类型', '民族', '入职日期', '试用月数', '转正薪资日期', '转正日期', '合同开始日期', '合同结束日期', '合同期限（年）', '是否部门领导', '紧急联系人', '与本人关系', '联系人电话', '是否已婚', '文化程度', '毕业学校', '专业', '户籍所在地', '现家庭住址','每月工作天数','每天工作（时）', '是否启用', '更新时间',];
            $body = [];
            $data = $model->select();
            foreach ($data as $item) {
                $record = [];
                $record['id'] = $item->id;
                $record['name'] = $item->name;
                $record['position_id'] = $item->position->name;
                $record['insure_id'] = $item->insure->insure;
                $record['job_number'] = $item->job_number;
                $record['mobile'] = $item->mobile.' ';
                $record['email'] = $item->email;
                $record['department_id'] = $item->department->name;
                $record['insurance_types'] = $item->insurance_types;
                $record['id_card'] = $item->id_card.' ';
                $record['sex'] = $item->sex_text;
                $record['age'] = $item->age;
                $record['birthday'] = $item->birthday;
                $record['birthday_month'] = $item->birthday_month;
                $record['node_type'] = $item->node_type;
                $record['nation'] = $item->nation;
                $record['hired_date'] = $item->hired_date;
                $record['trial_month'] = $item->trial_month;
                $record['full_salary_date'] = $item->full_salary_date;
                $record['full_date'] = $item->full_date;
                $record['contract_start_date'] = $item->contract_start_date;
                $record['contract_end_date'] = $item->contract_end_date;
                $record['contract_times'] = $item->contract_times;
                $record['is_leader'] = $item->is_leader_text;
                $record['emergency_contact'] = $item->emergency_contact;
                $record['emergency_contact_relation'] = $item->emergency_contact_relation;
                $record['emergency_contact_mobile'] = $item->emergency_contact_mobile;
                $record['marriage'] = $item->marriage==1?"已婚":"未婚";
                $record['education_level'] = $item->education_level;
                $record['education_school'] = $item->education_school;
                $record['major'] = $item->major;
                $record['domicile'] = $item->domicile;
                $record['current_address'] = $item->current_address;
                $record['days_per_month'] = $item->days_per_month;
                $record['hours_per_day'] = $item->hours_per_day;
                $record['status'] = $item->status_text;
                $record['update_time'] = $item->update_time;

                $body[] = $record;
            }
            return $this->exportData($header, $body, '员工-' . date('Y-m-d-H-i-s'));
        }
        $data = $model->paginate($this->admin['per_page'], false, ['query' => $request->get()]);
        if (isset($param['department_id']) && !empty($param['department_id'])) {
            $demodel = Department::get($param['department_id']);

            $this->assign('department_list', $this->getSelectList($demodel, $param['department_id']));
        } else {
            $this->assign('department_list', $this->getSelectList(new Department));
        }
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'staff_list' => Staff::all(),
            'position_list' =>Position::all(),
            'data' => $data,
            'page' => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, Staff $model, StaffValidate $validate)
    {
        if ($request->isPost()) {
            $param = $request->param();
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            $result = $model::create($param);

            $url = URL_BACK;
            if (isset($param['_create']) && $param['_create'] == 1) {
                $url = URL_RELOAD;
            }

            return $result ? success('添加成功', $url) : error();
        }

        $this->assign([
            'department_list' => $this->getSelectList(new Department),
            'position_list' => Position::all(),
            'insure' => Insure::all()
        ]);

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, Staff $model, StaffValidate $validate)
    {

        $data = $model::get($id);
        if ($request->isPost()) {
            $param = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            $result = $data->save($param);
            return $result ? success() : error();
        }
        if ($data['department']){
            $this->assign(
                ['department_list' => $this->getSelectList($data['department'], $data['department_id'])]
            );
        }else{
            $this->assign([
                'department_list' => $this->getSelectList(new Department),
            ]);
        }
        $this->assign([
            'data' => $data,
            'position_list' => Position::all(),
            'insure' => Insure::all()
        ]);
        return $this->fetch('add');

    }

    //删除
    public function del($id, Staff $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //启用
    public function enable($id, Staff $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 1]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }


//禁用
    public function disable($id, Staff $model)
    {
        $result = $model->whereIn('id', $id)->update(['status' => 0]);
        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //验证手机号是否唯一
    public function uniqueMobile(Staff $staff, Request $request){
        $mobile = $request->param('mobile');
        $params['mobile'] = $mobile;
        $count = $staff->where($params)->count();
        if ($count > 0) {
            return error('手机号已经存在，请重新输入');
        } else {
            return success('手机号可用');
        }
    }

}
